package cheme.ProcessEditor.Policies;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.swt.graphics.Color;

import cheme.ProcessModel.ProcessUnits.ProcessUnit;

public class ContainerHighlightEditPolicy extends org.eclipse.gef.editpolicies.GraphicalEditPolicy
{
	static final Color okBackground = new Color(null, 55,255,55);
	static final Color noBackground = new Color(null, 255,55,55);
	
	private Color revertColor;

	public void eraseTargetFeedback(Request request){
		if (revertColor != null){
			setContainerBackground(revertColor);
			revertColor = null;
		}
	}

	private Color getContainerBackground(){
		return getContainerFigure().getBackgroundColor();
	}

	private IFigure getContainerFigure(){
		return ((GraphicalEditPart)getHost()).getFigure();
	}

	public EditPart getTargetEditPart(Request request){
		return request.getType().equals(RequestConstants.REQ_SELECTION_HOVER) ?
			getHost() : null;
	}

	private void setContainerBackground(Color c){
		getContainerFigure().setBackgroundColor(c);
	}

	protected void showHighlight(RequestType requestType)
	{
		if(revertColor == null)
		{
			revertColor = getContainerBackground();
			
			ProcessUnit pu = (ProcessUnit)getHost().getModel();
			if(pu != null && 
				((RequestType.Source == requestType && pu.willAcceptInStream()) || 
				 (RequestType.Target == requestType && pu.willAcceptOutStream())))
			{
				setContainerBackground(okBackground);
			}
			else
			{
				setContainerBackground(noBackground);
			}
		}
	}

	private enum RequestType{Source, Target, Other};
	public void showTargetFeedback(Request request)
	{
		if(	request.getType().equals(RequestConstants.REQ_CONNECTION_START) ||
			request.getType().equals(RequestConstants.REQ_RECONNECT_SOURCE))
		{
			showHighlight(RequestType.Target);
		}
		else if(	request.getType().equals(RequestConstants.REQ_CONNECTION_END) ||
					request.getType().equals(RequestConstants.REQ_RECONNECT_TARGET))
		{
			showHighlight(RequestType.Source);
		}
		else if(	request.getType().equals(RequestConstants.REQ_MOVE) ||
				request.getType().equals(RequestConstants.REQ_ADD) ||
				request.getType().equals(RequestConstants.REQ_CLONE) ||
				request.getType().equals(RequestConstants.REQ_CREATE))
		{
			showHighlight(RequestType.Other);
		}
	}
}
